package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.utils.CookieUtils;
import com.fanrenqiji.common.utils.StringUtils;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月21日 下午3:10:58
 * @description 登录控制模块,
 */
@Controller
public class LoginController extends BaseController {
	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresUser
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		User user = UserUtils.getUser();
		// 未登录，则跳转到登录页
		if (user.getId() == null) {
			return "redirect:" + GlobalSetting.getAdminPath() + "/login";
		}
		// 登录成功后，验证码计算器清零
		isValidateCodeLogin(user.getLoginName(), false, true);

		return "modules/sys/sysIndex";
	}
	
	/**
	 * 引入Apache shiro过滤链
	 * 
	 * 登录管理
	 */
	@RequestMapping(value = "${adminPath}/{login:login;?.*}", method = RequestMethod.GET)
	public String login(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		// 如果已经登录，则跳转到管理首页
		if (user.getId() != null) {
			return "redirect:" + GlobalSetting.getAdminPath();
		}

		return "modules/sys/sysLogin";
	}

	/**
	 * Apache shiro过滤链
	 * 
	 * 用户和密码（包含验证码）令牌类UsernamePasswordToken校验登录
	 * 是否登录失败，真正登录的POST请求由FormAuthenticationFilter完成
	 */
	@RequestMapping(value = "${adminPath}/{login:login;?.*}", method = RequestMethod.POST)
	public String login(
			@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		User user = UserUtils.getUser();
		// 如果已经登录，则跳转到管理首页
		if (user.getId() != null) {
			return "redirect:" + GlobalSetting.getAdminPath();
		}
		// 绑定过滤的用户
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM,
				username);
		// 校验验证码
		model.addAttribute("isValidateCodeLogin",
				isValidateCodeLogin(username, true, false));
		return "modules/sys/sysLogin";
	}

	/**
	 * 退出登陆
	 * @param redirectAttributes 绑定退出信息“您已经安全退出”
	 * @return
	 */
	@RequestMapping(value="${adminPath}/logout",method = RequestMethod.GET)
	public String logout(RedirectAttributes redirectAttributes) {
		SecurityUtils.getSubject().logout();
		//TODO 退出页面是否需要
		return "redirect:" + GlobalSetting.getAdminPath();
	}

	/**
	 * 是否是验证码登录,通过验证码拦截一些非法刷页面操作。 通过用户名记录输错的次数，如果超过3次出错就会产生验证码。
	 * 
	 * @param useruame
	 *            通过用户名去校验验证码，
	 * @param isFail
	 *            如果是被登陆isFail为true，计数加1
	 * @param clean
	 *            计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail,
			boolean clean) {
		Map<String, Integer> loginFailMap = Maps.newHashMap();
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum == null) {
			loginFailNum = 0;
		}
		if (isFail) {
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean) {
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}
	
	
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme,
			HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isNotBlank(theme)) {
			CookieUtils.setCookie(response, "theme", theme);
		} else {
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:" + request.getParameter("url");
	}
}
